package cn.hanyx.coder.core.concurrent.juc.countdownlatch;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatchDemo
 *
 * @author hanyx
 * @date 2020/09/25
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        int threadNum = 10;
        CountDownLatch latch = new CountDownLatch(threadNum);
        for (int i = 0; i < threadNum; i++) {
            Thread task = new Thread(new TaskThread(latch));
            task.start();
        }
        System.out.println("Task Start!");
        latch.await();
        System.out.println("All Task is Done!");
    }
}

class TaskThread implements Runnable {

    private CountDownLatch latch;

    public TaskThread(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + " Task is Done");
            latch.countDown();
        }
    }
}